/*
 * Copyright 2011 Rolf Aden
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package com.ec;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.hadoop.conf.Configuration;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.tools.mapreduce.ConfigurationXmlUtil;
import com.google.appengine.tools.mapreduce.MapReduceServlet;

/**
 *	TODO check with the appengine-mapreduce-java team whether
 *	this functionality can be integrated into the MapReduceServlet itself.
 *  This Servelt could be removed afterwards.
 *
 * @author Rolf Aden
 */
@SuppressWarnings("serial")
public class CustomizedMapReduceServlet extends MapReduceServlet {

	private static final Logger log = Logger.getLogger(CustomizedMapReduceServlet.class.getName());

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		JSONObject retValue;

		if ("/mapreduce/start".equals(request.getRequestURI())) {
			try {
				Configuration config = ConfigurationXmlUtil
						.getConfigurationFromXml(request.getParameter("configuration"));
				String name = config.get("job.name");
				if (name == null) {
					name = "Automatically run request";
				}
				String jobId = handleStart(config, name, request);
				retValue = new JSONObject();
				retValue.put("mapreduce_id", jobId);
			} catch (Throwable t) {
				log.log(Level.SEVERE, "Got exception while running command", t);
				try {
					retValue = new JSONObject();
					retValue.put("error_class", t.getClass().getName());
					retValue.put("error_message", 
								 "Full stack trace is available in the server logs. Message: " 
								 + t.getMessage());
				} catch (JSONException e) {
					throw new RuntimeException("Couldn't create error JSON object", e);
				}
			}
			try {
				response.setContentType("application/json");
				retValue.write(response.getWriter());
				response.getWriter().flush();
			} catch (JSONException e) {
				throw new RuntimeException("Couldn't write command response", e);
			} catch (IOException e) {
				throw new RuntimeException("Couldn't write command response", e);
			}
		} else {
			super.doPost(request, response);
		}
	}
}
